/*
 * Author: Rico
 * Commit: 为节省代码长度, 所有用 malloc 开辟内存空间的操作
 *         都没有进行检验是否开辟成功, 请读者注意
*/

#include "linkedlist.h"

// ============================
//          无头结点
// ============================

void initListWithoutHeadNode(LinkList *head) {
    *head = NULL;
}

// 尾插创建链表
void appendCreateListWithoutHeadNode(LinkList *head) {
    *head = malloc(sizeof(LinkNode));
    (*head)->data = 1;
    (*head)->link = NULL;

    LinkNode *tmp = *head;
    for (int i = 2; i <= 10; i++) {
        LinkNode *newNode = malloc(sizeof(LinkNode));
        newNode->data = i;
        newNode->link = NULL;

        tmp->link = newNode;
        tmp = newNode;
    }
}

// 前插创建链表
void prependCreateListWithoutHeadNode(LinkList *head) {
    *head = malloc(sizeof(LinkNode));
    (*head)->data = 1;
    (*head)->link = NULL;
    
    for (int i = 2; i <= 10; i++) {
        LinkNode *newNode = malloc(sizeof(LinkNode));
        newNode->data = i;
        newNode->link = *head;
        *head = newNode;
    }
}

// 打印链表
void displayListWithoutHeadNode(LinkList head) {
    LinkNode *tmp = head;
    while (tmp->link != NULL) {
        printf("%d -- ", tmp->data);
        tmp = tmp->link;
    }
    printf("%d.\n", tmp->data);
}

// ============================
//          有头结点
// ============================

void initList(LinkList *head) {
    *head = malloc(sizeof(LinkNode));
    (*head)->data = 0;      // 这里用作记录链表结点个数, 也可以啥都不做
    (*head)->link = NULL;
}

void appendCreateList(LinkList *head) {
    LinkNode *tmp = *head;
    for (int i = 1; i <= 10; i++) {
        tmp = tmp->link = malloc(sizeof(LinkNode));
        tmp->data = i;
        tmp->link = NULL;
    }
}

void prependCreateList(LinkList *head) {
    for (int i = 1; i <= 10; i++) {
        LinkNode *newNode = malloc(sizeof(LinkNode));
        newNode->data = i;
        newNode->link = (*head)->link;

        (*head)->link = newNode;
        (*head)->data++;
    }
}

void displayList(LinkList head) {
    if (head->link == NULL) {
        printf("Nothing in the singly linked list.\n");
        return;
    }

    LinkNode *tmp = head->link;

    while (tmp->link != NULL) {
        printf("%d -- ", tmp->data);
        tmp = tmp->link;
    }

    // 若 head->data 头结点的数据域用作链表结点计数, 也可用下面的 for 循环输出链表
    // for (int i = 1; i < head->data; i++) {
    //     printf("%d --", tmp->data);
    //     tmp = tmp->link;
    // }

    printf("%d.\n", tmp->data);

}